
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;

using airwolf.SSDP;
using airwolf.HTTP;

namespace airwolf
{
	public class MediaServer: UPnPService, IHTTPHandler
	{
		private readonly ConnectionManager _connManager;
		private readonly ContentDirectory _directory;
		//private static string location = null;
		private readonly string _location;
        //private readonly int _port = 41014;

		public MediaServer()
		{
			_connManager = new ConnectionManager();
			_directory = new ContentDirectory();
            //IPAddress localAddress = IPAddress.Parse(address);
            _location = String.Format(@"http://{0}:{1}/MediaServer", IP.LocalAddress, Server.Port);
            //ST:urn:schemas-upnp-org:service:ContentDirectory:1\r\n
            SSDPClient.RegisterReferal(_directory.URN, _location);
            SSDPClient.RegisterReferal(URN, _location + "/ContentDirectory");
            ThreadPool.QueueUserWorkItem(StartNotify);
			//Listen();
		}

        private void StartNotify(object state)
        {
            for (int i = 0; i < 3; i++)
            {
                SSDPClient.Notify(URN, UUID, _location);
            }
        }

        public HTTPResult Handle(string URI, string HTTP)
        {
            Console.WriteLine("Received Handle request for {0}", URI);

            switch (URI.ToUpper())
            {
                case "/MEDIASERVER":
                    Console.WriteLine("Returning Media Server description");
                    return new HTTPResult(ServiceDescription, ContentTypes.TextXML);

                case "/MEDIASERVER/CONTENTDIRECTORY":

                    return new HTTPResult(_directory.ServiceDescription, ContentTypes.TextXML);

                default:

                    Console.WriteLine("Received Handle request for {0}", URI);
                    break;
            }
            
            return new HTTPResult("", ContentTypes.None);
        }

        public override string ServiceDescription
        {
            get
            {
                return Resource.MediaServer;
            }
        }

        public override string UUID
        {
            get
            {
                return "uuid:09565553-f9c7-4a85-84e1-1f35f6bede6a";
            }
        }

		public override string URN
		{
			get
			{
				return "urn:schemas-upnp-org:device:MediaServer:1";
			}
		}
	}
}
